var MemoryFileSystem = require("memory-fs");
var fs = new MemoryFileSystem(); // Optionally pass a javascript object
var request = require('superagent');
// 千万不要在这里require任何和stream想关的东西，容易circular dependency
var oReq = new XMLHttpRequest();
var yauzl = require("./yauzl-local");
oReq.open("GET", "/output.zip", true);
oReq.responseType = "arraybuffer";
var buffer = require('buffer');
var pt = require('path');
var Buffer = buffer.Buffer;
/*
var Writable = require('stream').Writable;
var ws = Writable();
ws._write = function (chunk, enc, next) {
    if (chunk !== null) {
      console.log(String(chunk));
      next();
    }
};
*/
var through = require('through');


oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    console.log([].slice.call(byteArray).map(function(x) {return x.toString(16)}));
    var buf = new Buffer(byteArray.length);
    for (var i = 0; i < byteArray.length; i++ ){
      buf.writeUInt8(byteArray[i], i);
    }
    yauzl.fromBuffer(buf, function(err, zipfile) {
      if (err) console.error(err);
      zipfile.on("entry", function(entry) {
        console.log(entry);
        zipfile.openReadStream(entry, function(err, readStream) {
          if (err) throw err;
          var ws = through(write, end);

          var filebuf = '';
          function write (buf) {
              filebuf += String(buf);
          }
          function end () {
              fs.mkdirpSync(pt.dirname('/' + entry.fileName));
              fs.writeFileSync("/" + entry.fileName, filebuf);
          }

          console.log('filename:', entry.fileName)
          // ensure parent directory exists, and then:
          readStream.pipe(ws);
        });
      });
      zipfile.once("end", function() {
      //  zipfile.close();
        var x = fs.readdirSync("/");
        console.log(x);
      });
  });
}
};

oReq.send(null);


/*
request.get('/x.zip')
  .header('Content-Type': 'application/octet-stream')
  .end(function(err ,res) {
    debugger;
    var buffer = res.text.toStr
    zlib.unzip(buffer, function(err, buffer) {
      if (!err) {
        console.log(buffer.toString());
      } else {
        console.error(err)
      }
    });

  });
*/
